package com.shanzmoo.h5.web;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.db.personnel.entity.MemberInfoEntity;
import com.shanzmoo.db.personnel.entity.WechatConfigData;
import com.shanzmoo.db.personnel.entity.dto.MemberAddressSaveDto;
import com.shanzmoo.db.personnel.entity.dto.MemberAddressUpdateDto;
import com.shanzmoo.db.personnel.entity.dto.MemberInvoiceSaveDto;
import com.shanzmoo.db.personnel.entity.vo.MallMemberInfoVo;
import com.shanzmoo.db.personnel.entity.vo.MemberAddressVo;
import com.shanzmoo.db.personnel.entity.vo.MemberInvoiceVo;
import com.shanzmoo.db.personnel.service.IMemberAddressService;
import com.shanzmoo.db.personnel.service.IMemberInfoService;
import com.shanzmoo.db.personnel.service.IMemberInvoiceService;
import com.shanzmoo.h5.domain.bo.WxAuthAccessTokenBO;
import com.shanzmoo.h5.util.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 会员服务-会员管理
 *
 * @author Gzhao 2021/1/3
 */
@Slf4j
@Api(tags = "会员服务-会员管理")
@RestController
@RequestMapping("member")
public class MemberController {

    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IMemberInvoiceService memberInvoiceService;

    @ApiOperation(value = "获取会员详细信息")
    @GetMapping("/info")
    public SHttpResponse<MallMemberInfoVo> getMemberInfo() {
        MallMemberInfoVo member = memberInfoService.getMemberInfo(SecurityUtil.getCurrentMemeberId());
        return SHttpResponse.ok(member);
    }

    @ApiOperation(value = "更新会员微信身份")
    @GetMapping("/updateWxInfo")
    public SHttpResponse<String> updateWxInfo(@RequestParam String code) {
        MemberInfoEntity member = memberInfoService.getById(SecurityUtil.getCurrentMemeberId());

        if (StrUtil.isNotBlank(member.getOpenId())){
            return SHttpResponse.ok(member.getOpenId());
        }

        String url = WechatConfigData.QUTHORIZE_URL
                + "?appid=" + WechatConfigData.appId
                + "&secret=" + WechatConfigData.appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";

        String response= HttpUtil.get(url);
        log.info("请求access_token结果：{}", response);

        JSONObject resultJson = JSON.parseObject(response);

        if (ObjectUtil.isNotEmpty(resultJson.get("errcode"))){
            Integer errCode = (Integer)resultJson.get("errcode");
            String errMsg = (String)resultJson.get("errmsg");

            log.error("获取微信网页授权 access_token 失败，返回结果：{}", resultJson);
            return SHttpResponse.fail(Constant.ERRCODE_LOGIC, "获取网页授权access_token失败, errcode: " + errCode
                    + ", errmsg: " + errMsg);
        }
        WxAuthAccessTokenBO accessTokenBO = JSON.parseObject(resultJson.toJSONString(), WxAuthAccessTokenBO.class);

        member.setOpenId(accessTokenBO.getOpenid());

        getWxUserInfo(accessTokenBO.getAccessToken(), accessTokenBO.getOpenid(), member);
        memberInfoService.updateById(member);

        return SHttpResponse.ok(member.getOpenId());
    }

    @ApiOperation(value = "新增会员地址")
    @PostMapping("/add/address")
    public SHttpResponse<Boolean> addAddress(@RequestBody MemberAddressSaveDto saveDto) {
        memberAddressService.addAddress(String.valueOf(SecurityUtil.getCurrentMemeberId()), saveDto);
        return SHttpResponse.ok(Boolean.TRUE);
    }

    @ApiOperation(value = "会员地址列表")
    @GetMapping("/address/list")
    public SHttpResponse<List<MemberAddressVo>> getAddressList() {
        List<MemberAddressVo> list = memberAddressService.getAddressList(String.valueOf(SecurityUtil.getCurrentMemeberId()));
        return SHttpResponse.ok(list);
    }

    @ApiOperation(value = "删除")
    @GetMapping("/delete/address")
    public SHttpResponse<Boolean> deleteById(@ApiParam(value = "地址id") @RequestParam(value = "id") Integer id) {
        SResponse<Boolean> re = memberAddressService.deleteById(id, String.valueOf(SecurityUtil.getCurrentMemeberId()));
        return SHttpResponse.transform(re);
    }

    @ApiOperation(value = "修改会员地址")
    @PostMapping("/update/address")
    public SHttpResponse<Boolean> updateAddress(@RequestBody MemberAddressUpdateDto updateDto) {
        memberAddressService.updateAddress(String.valueOf(SecurityUtil.getCurrentMemeberId()), updateDto);
        return SHttpResponse.ok(Boolean.TRUE);
    }

    @ApiOperation(value = "新增发票地址")
    @PostMapping("/add/invoice")
    public SHttpResponse<Boolean> addInvoice(@RequestBody MemberInvoiceSaveDto saveDto) {
        memberInvoiceService.addInvoice(String.valueOf(SecurityUtil.getCurrentMemeberId()), saveDto);
        return SHttpResponse.ok(Boolean.TRUE);
    }

    @ApiOperation(value = "获取用户发票地址")
    @GetMapping("/getInvoice")
    public SHttpResponse<MemberInvoiceVo> obtianInvoice() {
        MemberInvoiceVo memberInvoiceVo = memberInvoiceService.obtianInvoice(String.valueOf(SecurityUtil.getCurrentMemeberId()));
        return SHttpResponse.ok(memberInvoiceVo);
    }

    /**
     * 获取微信用户信息
     *
     * @author Gzhao 2021/1/25
     * @param
     * @return
     */
    private void getWxUserInfo(String accessToken, String openid, MemberInfoEntity member) {
        try {
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid
                    + "&lang=zh_CN";

            String response= HttpUtil.get(url);
            log.info("请求userInfo结果：{}", response);

            Map userInfoMap = JSON.parseObject(response, Map.class);

            if (ObjectUtil.isNotEmpty(userInfoMap)){

                String avatarUrl = (String) userInfoMap.get("headimgurl");
                String nickname = (String) userInfoMap.get("nickname");

                member.setNickname(nickname);
                member.setAvatarUrl(avatarUrl);
            }

        } catch (Exception e){
            log.error("获取微信用户信息异常", e);
        }
    }

}
